package com.dmooo.ymx.login;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TextInputEditText;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.dmooo.ymx.CaiNiaoApplication;
import com.dmooo.ymx.R;
import com.dmooo.ymx.base.BaseActivity;
import com.dmooo.ymx.bean.AccPass;
import com.dmooo.ymx.bean.UserBean;
import com.dmooo.ymx.common.ACache;
import com.dmooo.ymx.common.CommonUtils;
import com.dmooo.ymx.common.LogUtils;
import com.dmooo.ymx.common.SPUtils;
import com.dmooo.ymx.config.Constants;
import com.dmooo.ymx.https.HttpUtils;
import com.dmooo.ymx.utils.ListDataSave;
import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.lljjcoder.style.citylist.Toast.ToastUtils;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cz.msebera.android.httpclient.Header;

import static com.dmooo.ymx.common.SPUtils.sp;

public class LoginActivity extends BaseActivity  {
    @BindView(R.id.et_account)
    TextInputEditText et_account;
    @BindView(R.id.et_psd)
    TextInputEditText et_psd;
    @BindView(R.id.tv_forgotpsd)
    TextView tv_forgotpsd;
    @BindView(R.id.tv_login)
    TextView tv_login;
    private ACache mAcache;
    public static Activity activity;

    SharedPreferences.Editor editor = sp.edit();
    AccPass user;
    List<AccPass> classTests;
    String uid="";

    ListDataSave dataSave;
    private List<Object> listBean;
    private ArrayList<String> listString;
    private ArrayList<Map<String, Object>> listMap;

    @Override
    protected void initUI() {
        setContentView(R.layout.ac_login);
        ButterKnife.bind(this);
        activity=this;
        dataSave = new ListDataSave(LoginActivity.this, "baiyu");
        listString = new ArrayList<String>();
        listBean = new ArrayList<>();
        listMap = new ArrayList<Map<String, Object>>();
    }
    @Override
    protected void initData() {
        mAcache = ACache.get(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(getIntent().getStringExtra("acount")!=null){
            et_account.setText(getIntent().getStringExtra("acount"));
            et_psd.setText(getIntent().getStringExtra("password"));
        }else{
            et_account.setText(SPUtils.getStringData(this, "phone", ""));
            et_psd.setText(SPUtils.getStringData(this, "pwd", ""));
        }
    }
    @Override
    protected void initListener() {
        //忘记密码
        tv_forgotpsd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openActivity(RetrievePasswordActvity.class);
            }
        });
        tv_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String account = getTextEditValue(et_account);
                String psd = getTextEditValue(et_psd);
                getData(account, psd);
            }
        });
    }
    @Override
    public void onBack(View v) {

    }
    /**
     * 登录
     */
    private void getData(final String phone, final String psd) {
        if (!CommonUtils.isNetworkAvailable()) {
            showToast(getResources().getString(R.string.error_network));
            return;
        }
//        if(!CheckUtil.isMobile(phone)){
//            T.showShort(LoginActivity.this, "请输入正确的手机号");
//            return;
//        }
        RequestParams params = new RequestParams();
        params.put("account", phone);
//        final DesUtil desUtil = new DesUtil(DesUtil.SECURITY_PRIVATE_KEY);
//        params.put("password", desUtil.encrypt(pwd));//登录密码
        params.put("pwd", psd);
        HttpUtils.post(Constants.LOGIN, params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                // 输出错误信息
                LogUtils.e(TAG, "onFailure()--" + responseString);
            }

            @Override
            public void onFinish() {
                // 隐藏进度条
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {

                LogUtils.e(TAG, "onSuccess()--" + responseString);
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    //返回码
                    int code = jsonObject.optInt("code");
                    //返回码说明
                    String msg = jsonObject.optString("msg");
                    //用户ID
                    uid = jsonObject.optString("uid");
                    //用户组ID
                    String group_id = jsonObject.optString("group_id");
                    //用户身份令牌，作为其它所有用户接口的必填参数，请APP本地化保存
                    String token = jsonObject.optString("token");
                    if (0 == code) {
                        SPUtils.saveStringData(LoginActivity.this, "phone", et_account.getText().toString());
                        SPUtils.saveStringData(LoginActivity.this, "pwd", et_psd.getText().toString());
                        SPUtils.saveStringData(LoginActivity.this, "uid", uid);
                        mAcache.put(Constants.TOKEN, token);
                        mAcache.put(Constants.GROUP_ID, group_id);
                        mAcache.put(Constants.ACCOUT, phone);
                        mAcache.put(Constants.PASSWORD, psd);

                        user = new AccPass();
//                        if(dataSave.getDataList("javaBean").size()>0){
                        listBean=dataSave.getDataList("javaBean");
                        if(getIntent().getStringExtra("acount")!=null){

                        }else{
                            if(listBean.contains(phone)){

                            }else{
                                user.setAccount(phone);
                                user.setPassword(psd);
                                listBean.add(user);
                                dataSave.setDataList("javaBean",listBean);
                            }
                        }
                        SPUtils.saveStringData(LoginActivity.this, "token",token);
                        CaiNiaoApplication.setUserBean(new UserBean(uid, group_id, token));
                        SPUtils.saveStringData(LoginActivity.this, Constants.TOKEN, token);
                        SPUtils.saveStringData(LoginActivity.this, Constants.UID, uid);

                        Log.d("LOGINPASS",SPUtils.getStringData(LoginActivity.this,"phone",""));
                        Log.d("LOGINPASS",SPUtils.getStringData(LoginActivity.this,"pwd",""));
                        JPushInterface.setAlias(LoginActivity.this, uid,
                        new TagAliasCallback() {//回调接口,i=0表示成功,其它设置失败
                            @Override
                            public void gotResult(int responseCode, String s, Set<String> set) {
                                if (responseCode==0) {
                                    System.out.println("jpush alias@@@@@别名设置成功");
                                }
                            }
                        });
                        loginHandle.sendEmptyMessage(0);
                        //发送登录成功的消息
                        // BroadcastManager.getInstance(IndexActivity.this).sendBroadcast(BroadcastContants.sendLoginMessage);
//                        Bundle bundle=new Bundle();
//                        bundle.putInt("type",3);
                        // openActivity(MainActivity.class);
                        SPUtils.saveStringData(LoginActivity.this, "is", "1");
                        if(getIntent().getStringExtra("acount")!=null){

                        }else{
                            WelActivity.activity.finish();
                            WelActivity.activity = null;
                        }
                        finish();
                    } else {
                        ToastUtils.showShortToast(LoginActivity.this, msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("服务器错误");
                }
            }

            @Override
            public void onStart() {
                // 显示进度条
                super.onStart();
                showLoadingDialog();
            }
        });

    }

    private void loginHuanxin() {
        try{
            EMClient.getInstance().login(""+uid, "123456", new EMCallBack() {//回调
                @Override
                public void onSuccess() {
                    EMClient.getInstance().groupManager().loadAllGroups();
                    EMClient.getInstance().chatManager().loadAllConversations();
                     Log.d("main", "登录聊天服务器成功！");
                    SPUtils.put(LoginActivity.this, "new", "1");
                    finish();
                }

                @Override
                public void onProgress(int progress, String status) {

                }

                @Override
                public void onError(int code, String message) {
                    if(message.contains("already login")){
                        EMClient.getInstance().logout(true);
                        loginHandle.sendEmptyMessage(0);
                    }else{
                        handler.sendEmptyMessage(0);
                    }
                    Log.d("main", "登录聊天服务器失败！" + code+"  "+message);
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private Handler loginHandle=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            loginHuanxin();
        }
    };
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            createChat();
        }
    };

    private void createChat() {
        RequestParams params = new RequestParams();
        params.put("token", SPUtils.get(this, SPUtils.getStringData(LoginActivity.this,"token",""), "").toString());
        HttpUtils.post(Constants.APP_IP+"/app.php?c=Huanxin&a=createUser", params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                // 输出错误信息
                LogUtils.e(TAG, "onFailure()--" + responseString);
            }

            @Override
            public void onFinish() {
                // 隐藏进度条
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    if(jsonObject.getInt("code")==2){
                        showToast("登录聊天服务器失败");
//                        EMClient.getInstance().logout(true);
//                        loginHandle.sendEmptyMessage(0);
                    }else{
                        loginHandle.sendEmptyMessage(0);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStart() {
                // 显示进度条
                super.onStart();
                showLoadingDialog();
            }
        });
    }


    /**
     * 保存List
     *
     * @param tag
     * @param datalist
     */
    public void setDataList(String tag, List<AccPass> datalist) {
        if (null == datalist || datalist.size() <= 0)
            return;

        Gson gson = new Gson();
        //转换成json数据，再保存
        String strJson = gson.toJson(datalist);
        editor.clear();
        editor.putString(tag, strJson);
        editor.commit();
    }


    @OnClick({R.id.back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
        }
    }

}
